package com.bigfans.catalogservice.service.product;

import com.bigfans.catalogservice.api.clients.SystemServiceClient;
import com.bigfans.catalogservice.dao.ProductImageDAO;
import com.bigfans.catalogservice.model.ImageGroup;
import com.bigfans.catalogservice.model.Product;
import com.bigfans.catalogservice.model.ProductImage;
import com.bigfans.catalogservice.model.entity.ProductImageEntity;
import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.model.SystemSetting;
import com.bigfans.framework.plugins.FileStoragePlugin;
import com.bigfans.framework.plugins.PluginManager;
import com.bigfans.framework.utils.FileUtils;
import com.bigfans.framework.utils.IOUtils;
import com.bigfans.framework.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service(ProductImageServiceImpl.BEAN_NAME)
public class ProductImageServiceImpl extends BaseServiceImpl<ProductImage> implements ProductImageService {
	
	public static final String BEAN_NAME = "productImageService";
	
	@Autowired
	private ProductService productService;
	@Autowired
	private SystemServiceClient systemServiceClient;
	
	private ProductImageDAO productImageDAO;
	
	@Autowired
	public ProductImageServiceImpl(ProductImageDAO productImageDAO) {
		super(productImageDAO);
		this.productImageDAO = productImageDAO;
	}
	
	public void upload(ProductImage image, InputStream is) throws Exception {
		this.upload(image, is, null);
	}
	
	public void upload(ProductImage image, InputStream is , FileUploadCallback callback) throws Exception {
		File tempFile = new File(FileUtils.getTempDirectory(), UUID.randomUUID() + "." + image.getExt());
		IOUtils.copyToFile(is, tempFile);
		upload(image, tempFile, callback);
	}
	
	@Override
	public void upload(ProductImage image, File srcFile) throws Exception {
		upload(image, srcFile, null);
	}
	
	@Transactional
	public void upload(List<ProductImage> imageList) throws Exception {
		for (int i = 0;i<imageList.size() ; i++) {
			ProductImage pi = imageList.get(i);
			pi.setOrderNum(i + 1);
			String path = pi.getPath();
			FileStoragePlugin fsPlugin = PluginManager.getFileStoragePlugin();
			File srcFile = null;
			try {
				srcFile = fsPlugin.download(path);
				upload(pi, srcFile);
			} catch (Exception e) {
				throw new RuntimeException("upload image error");
			} finally {
				if(srcFile != null){
					srcFile.deleteOnExit();
				}
				fsPlugin.deleteFile(path);
			}
			if(i == 0){
				
			}
		}
	}
	
	@Transactional
	public void upload(ProductImage image, File srcFile , FileUploadCallback callback) throws Exception {
		FileStoragePlugin fsPlugin = PluginManager.getFileStoragePlugin();
		// 获取图片存储路径
		String folderPath = "images/itemservice/"+image.getProdId()+"/";
		List<ProductImage> imageList = new ArrayList<ProductImage>();
		File largeTempFile = FileUtils.newTempFile("L_" + srcFile.getName());
		File middleTempFile = FileUtils.newTempFile("M_" + srcFile.getName());
		File smallTempFile = FileUtils.newTempFile("S_" + srcFile.getName());
		try {
			// 大图片
			ProductImage largeImg = image.clone();
			largeImg.setType(ProductImage.TYPE_LARGE);
			largeImg.setPath(folderPath +File.separator+ largeTempFile.getName());
			ImageUtils.compress(srcFile,largeTempFile,ProductImage.SIZE_WEIDTH_L, ProductImage.SIZE_HEIGHT_L);
			
			//中图片
			ProductImage middleImg = image.clone();
			middleImg.setType(ProductImage.TYPE_MIDDLE);
			middleImg.setPath(folderPath + middleTempFile.getName());
			ImageUtils.compress(srcFile,middleTempFile, ProductImage.SIZE_WEIDTH_M, ProductImage.SIZE_HEIGHT_M);
			
			//小图片
			ProductImage smallImg = image.clone();
			smallImg.setType(ProductImage.TYPE_SMALL);
			smallImg.setPath(folderPath + smallTempFile.getName());
			ImageUtils.compress(srcFile,smallTempFile, ProductImage.SIZE_WEIDTH_S, ProductImage.SIZE_HEIGHT_S);
			
			fsPlugin.upload(largeTempFile,folderPath + largeTempFile.getName());
			fsPlugin.upload(middleTempFile,folderPath + middleTempFile.getName());
			fsPlugin.upload(smallTempFile,folderPath + smallTempFile.getName());
			
			if(callback != null){
				callback.onComplete(folderPath + largeTempFile.getName() , largeTempFile);
				callback.onComplete(folderPath + middleTempFile.getName() , middleTempFile);
				callback.onComplete(folderPath + smallTempFile.getName() , smallTempFile);
			}
			imageList.add(largeImg);
			imageList.add(middleImg);
			imageList.add(smallImg);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			largeTempFile.deleteOnExit();
			middleTempFile.deleteOnExit();
			smallTempFile.deleteOnExit();
		}
		
		//保存到数据库
		this.batchCreate(imageList);
	}
	
	/**
	 * 商品默认缩略图
	 * @param prodId
	 * @return
	 */
	public ProductImage getThumb(String prodId) throws Exception{
		ProductImage thumb = productImageDAO.getThumb(prodId);
		return thumb;
	}
	
	@Override
	public void uploadThumb(ProductImage image, InputStream is) throws Exception {
		FileStoragePlugin fsPlugin = PluginManager.getFileStoragePlugin();
		// 获取图片存储路径
		SystemSetting systemSettings = systemServiceClient.getSystemSetting();
//		String uploadBasePath = systemSettings.getUploadImagePath();
		String folderPath = new StringBuilder("/upload/images")
								.append(File.separator).append("pg").append(File.separator)
								.append(image.getPgId()).append(File.separator)
								.append("itemservice").append(File.separator)
								.append(image.getProdId()).toString();
		
		File middleTempFile = new File(FileUtils.getTempDirectory(), ProductImageEntity.TYPE_THUMB + "_" +UUID.randomUUID() + "." + image.getExt());
		try {
			//  上传缩略图
			ImageUtils.compress(is ,middleTempFile, ProductImageEntity.SIZE_WEIDTH_M, ProductImageEntity.SIZE_HEIGHT_M);
			fsPlugin.upload(middleTempFile ,folderPath);
			middleTempFile.deleteOnExit();
			Product product = new Product();
			product.setId(image.getProdId());
			product.setImagePath(folderPath +File.separator+ middleTempFile.getName());
			productService.update(product);
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			middleTempFile.delete();
			IOUtils.closeQuietly(is);
		}
	}
	@Override
	public List<ImageGroup> listProductImages(String productId) {
		return productImageDAO.listWithGroup(productId);
	}
}
